package rsj.service.export;

import com.alibaba.excel.ExcelWriter;
import common.exec.RsjIllegalArgueException;
import common.util.http.HttpUtil;
import common.util.http.UploadFileResponseBody;
import common.util.http.UploadFileResponseData;
import rsj.context.ApplicationContextUtil;
import rsj.properties.FileServiceProperties;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.util.Optional;

/**
 * 将文件写入流上传文件服务器的方法
 *
 * @author yuanqinglong
 * @since 2021/3/17 17:31
 */
public interface IWriteUploadFileMethod {


    /**
     * 将生成的文件写入输出流
     *
     * @param jsonString 查询的数据
     * @param sheetName  导出的工作表名称
     * @return 写入文件的路径
     */
    default OutputStream writeDataToTheOutputStream(String jsonString, String sheetName){
        return null;
    }


    /**
     * 写数据到excel
     *
     * @param jsonData    json数据
     * @param excelWriter excel
     * @param sheetNum    表num
     */
    default void writeDataToTheExcelWriter(String jsonData, ExcelWriter excelWriter, int sheetNum){

    }


    /**
     * 将生成的文档上传到文件服务
     *
     * @param outputStream   文件输出流
     * @param exportFileName 导出的文件名称
     * @return 文件服务返回的文件id
     */
    default UploadFileResponseData uploadToFileService(OutputStream outputStream, String exportFileName) {
        String uploadUrl = ApplicationContextUtil.getBean(FileServiceProperties.class).getFileServiceUploadUrl();
        UploadFileResponseBody responseBody = HttpUtil.uploadFile(uploadUrl, exportFileName, "$file", outputStreamToInputStream(outputStream));
        return Optional.ofNullable(responseBody).map(UploadFileResponseBody::getData).orElseThrow(() -> new RsjIllegalArgueException("文件生成失败"));
    }


    /**
     * OutputStream转InputStream
     *
     * @param out 输出流
     * @return 输入流
     */
    static ByteArrayInputStream outputStreamToInputStream(OutputStream out) {
        ByteArrayOutputStream byteArrayOutputStream = (ByteArrayOutputStream) out;
        return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
    }
}
